package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
//@Transactional
public class RegionServiceImpl implements IRegionService {

	@Autowired
	private RegionRepository regionRepository;

	@Autowired
	private MongoTemplate template;

	@Override
	public void save(Region region) {
		region.setId(null);
		regionRepository.save(region);
	}

	@Override
	public void update(Region region) {
		regionRepository.save(region);
	}

	@Override
	public void delete(String id) {
		regionRepository.deleteById(id);
	}

	@Override
	public Region get(String id) {
		return regionRepository.findById(id).orElse(null);
	}

	@Override
	public Page<Region> query(RegionQuery qo) {
		Query query = new Query();


		return PageUtils.page(template,query ,Region.class, qo,Sort.by(Sort.Direction.ASC,"_id"));
	}

	@Override
	public List<Region> findByHotRegion() {
		return regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
	}

	@Override
	public List<String> getDestByRegionId(String rid) {
		Region region = this.get(rid);
		return region.getRefIds();
	}

	@Override
	public void changeHotValue(String id, Integer hot) {
		// 方式一
	/*	Region region = this.get(id);
		region.setIshot(hot);
		this.update(region);*/

		// 方式二
		// 拼接查询条件
		Query query = new Query();
		query.addCriteria(Criteria.where("_id").is(id));
		// 拼接修改的内容
		Update update = new Update();
		update.set("ishot",hot);
		// 执行修改语句,并指定哪张表
		// 参数1: 查出来,参数2: 修改,参数3: 哪张表
		template.updateMulti(query,update,Region.class);
	}

	@Override
	public List<Region> list() {
		return regionRepository.findAll();
	}
}
